/**
 *
 */
package com.zznode.client.wlanpolling.test;

import java.util.HashMap;
import java.util.Map;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.TimeSeries;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zznode.client.wlanpolling.R;
import com.zznode.client.wlanpolling.WLANPollingApplication;
import com.zznode.client.wlanpolling.WLanContext;
import com.zznode.client.wlanpolling.model.SystemSetting;
import com.zznode.client.wlanpolling.model.TestResultConstants;
import com.zznode.client.wlanpolling.model.WLANPollManager;
import com.zznode.client.wlanpolling.utils.NetworkUtils;
import com.zznode.client.wlanpolling.utils.PingExecuteListener;
import com.zznode.client.wlanpolling.utils.PingExecuteTask;
import com.zznode.client.wlanpolling.utils.ThroughtOuputputRatesExceuteListener;
import com.zznode.client.wlanpolling.utils.ThroughtOuputputRatesExceuteTask;
import com.zznode.client.wlanpolling.utils.PingUtils;
import com.zznode.client.wlanpolling.utils.WLanPollingUtils;

/**
 * @author Bean
 * 
 */
public class PollAutoTestActivity extends Activity implements
		PingExecuteListener, ThroughtOuputputRatesExceuteListener {
	public static final int UPDATE_HIT = 1;
	public static final int UPDATE_DHCP_INFO = 2;
	public static final int UPDATE_PING_GATEWAY = 3;
	public static final int UPDATE_PING_ADSL = 4;
	public static final int UPDATE_THROUGHTOUT_CHART = 5;
	public static final int UPDATE_BUTTON_STATUS = 6;

	private WifiManager wifiManager;
	private Button btnReDhcpTest;
	private Button btnStartTest;
	private Button btnPingTest;
	private Button btnThroughtputRates;
	private TextView txtHit;
	private TextView txtIp;

	private TextView txtPingCmd2;
	private TextView txtPingCmd1;

	private WifiBroadcastReceiver wifiReceiver;

	private EnumAutoTestStatus currentStatus;
	private EnumAutoTestStatus innerStatus;

	private EnumAutoTestStatus[] autoTestSteps = new EnumAutoTestStatus[] {
			EnumAutoTestStatus.AUTO_TEST_DHCP,
			EnumAutoTestStatus.AUTO_TEST_THROUGHTRATES,
			EnumAutoTestStatus.AUTO_TEST_PING };

	private EnumAutoTestStatus currentStep;
	private int currentAutoTestStepIndex = 1;

	private Thread autoTestThread;

	private WLANPollingApplication application;

	private UpdateUIHandler updateUIHandler;

	private XYMultipleSeriesDataset dataset;
	private GraphicalView chartView;

	private TextView txtWebAverageSpeed;
	private TextView txtWebPeekSpeed;
	private TextView txtWebDownloadUrl;

	/**
	 * 测试结果
	 */
	private String apIp = "192.168.1.1";
	
	private long reDhcpTime;
	//private long throughtoutputRateSpeed;
	//平均速度 峰值速度
	private long throughtoutputRateAverageSpeed;
	private long throughtoutputRatePeakSpeed;
	
	//网关测试结果 包括丢包数、丢包率、最大时延、最小时延、平均时延
	private String gatewayIp;
	private String gatewayDelay;
	private String gatewayMaxDelay;
	private String gatewayMinDelay;
	private String gatewayLost;
	private String gatewayPkgLost;
	
	//宽带测试结果
	private String adslIp;
	private String adslDelay;
	private String adslMaxDelay;
	private String adslMinDelay;
	private String adslLost;
	private String adslPkgLost;
	
	XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer();
	private double rendererMaxY = 10.0;
	private double rendererMaxX = 50.0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.polltest_auto);
		application = (WLANPollingApplication) getApplication();

		wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

		bindEvent();
		bindView();

		// listen wifi status
		wifiReceiver = new WifiBroadcastReceiver();
		registerReceiver(wifiReceiver, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));

		currentStatus = EnumAutoTestStatus.NOTSTART;
		currentStep = EnumAutoTestStatus.NOTSTART;
		Looper looper = Looper.myLooper();
		updateUIHandler = new UpdateUIHandler(looper);

		initData();
	}

	private void initData() {
		txtWebAverageSpeed.setText("");
		txtWebPeekSpeed.setText("");
		txtWebDownloadUrl.setText("路径:" + application.getContext().getSystemSetting().getThroughtoutputTestUrl());
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		unregisterReceiver(wifiReceiver);
	}
	
	private void bindView() {
		Button btnBeginTest = (Button) findViewById(R.id.beginTest);
		btnBeginTest.setVisibility(View.VISIBLE);
		
		txtHit = (TextView) findViewById(R.id.testHit);
		txtIp = (TextView) findViewById(R.id.txtIp);
		txtPingCmd1 = (TextView) findViewById(R.id.txtPingCmd1);
		txtPingCmd2 = (TextView) findViewById(R.id.txtPingCmd2);

		txtWebAverageSpeed = (TextView)findViewById(R.id.txtWebAverageSpeed);
		txtWebPeekSpeed = (TextView)findViewById(R.id.txtWebPeekSpeed);
		txtWebDownloadUrl = (TextView)findViewById(R.id.txtWebDownloadUrl);
		
		apIp = NetworkUtils.intToIp(wifiManager.getDhcpInfo().ipAddress); 
		txtIp.setText(apIp);
		
		LinearLayout layout = (LinearLayout) findViewById(R.id.throughtoutRateChartPlaceHolder);
		dataset = new XYMultipleSeriesDataset();

		TimeSeries series = new TimeSeries("Throughtoutput Rates");

		dataset.addSeries(series);

		XYSeriesRenderer r = new XYSeriesRenderer();
		r.setColor(Color.GREEN);
		r.setPointStyle(PointStyle.POINT);

		renderer.addSeriesRenderer(r);
		renderer.setShowGridX(true);
		renderer.setXAxisMax(rendererMaxX);
		renderer.setXAxisMin(0);
		renderer.setShowGrid(true);
		renderer.setShowAxes(true);
		renderer.setYAxisMax(1024);
		renderer.setYAxisMin(0);
		renderer.setPanEnabled(true, false);
		renderer.setZoomEnabled(false);
		renderer.setShowLabels(true);
		renderer.setShowLegend(false);
		renderer.setXTitle("time(s)");
		renderer.setYTitle("speed(kbps)");
		renderer.setFitLegend(true);
		renderer.setGridColor(Color.DKGRAY);
		renderer.setMarginsColor(Color.argb(0, 0xff, 0, 0));
		renderer.setBackgroundColor(Color.TRANSPARENT); // 设置背景色透明
		renderer.setPanEnabled(false);
		renderer.setClickEnabled(false);
		renderer.setInScroll(true);
		renderer.setPanEnabled(false, false);
		renderer.setZoomEnabled(false);
		
		for(int i = 0; i < rendererMaxX; i++) {
			if(i % 5 == 0)
				renderer.addXTextLabel(i, i + "");
		}
		
		chartView = ChartFactory.getTimeChartView(this, dataset, renderer, "");
		layout.addView(chartView, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));

		layout.requestLayout();
	}

	private void bindEvent() {
		btnStartTest = (Button) findViewById(R.id.beginTest);
		btnStartTest.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				txtPingCmd1.setText("");
				txtPingCmd2.setText("");
				startAutoTest();
			}
		});

		btnReDhcpTest = (Button) findViewById(R.id.reIpTest);
		btnReDhcpTest.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				currentStatus = EnumAutoTestStatus.RE_TEST_DHCP;
				updateHit();
				startToTestDhcp();
			}
		});

		btnPingTest = (Button) findViewById(R.id.retPingGateway);
		btnPingTest.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				txtPingCmd1.setText("");
				txtPingCmd2.setText("");
				currentStatus = EnumAutoTestStatus.RE_TEST_PING;
				startToTestPing();
			}
		});

		btnThroughtputRates = (Button) findViewById(R.id.retThroughputRate);
		btnThroughtputRates.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dataset.getSeriesAt(0).clear();
				currentStatus = EnumAutoTestStatus.RE_TEST_THROUGHTRATES;
				startToTestThroughtOutRates();
			}
		});
		
		Button btnSave = (Button) findViewById(R.id.btnSave);
		btnSave.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {				
				WLanContext context = application.getContext();
				Map<String, Object> values = new HashMap<String, Object>();
				
				values.put(TestResultConstants.IPADDRESS, apIp);
				//values.put(TestResultConstants.AVERAGERATE, throughtoutputRateAverageSpeed/1024 + "KB/s");
				//values.put(TestResultConstants.PEEKRATE, throughtoutputRatePeakSpeed/1024 + "KB/s");
				values.put(TestResultConstants.AVERAGERATE, throughtoutputRateAverageSpeed/1024 + "");
				values.put(TestResultConstants.PEEKRATE, throughtoutputRatePeakSpeed/1024 + "");
				values.put(TestResultConstants.APNETTIMELOG, gatewayDelay);
				// values.put(TestResultConstants.APNETLOSS , gatewayDelay);
				values.put(TestResultConstants.APNETLOSS , gatewayLost);
				values.put(TestResultConstants.NETSKYTIMELOG, adslDelay);
				values.put(TestResultConstants.NETSKYLOSS, adslLost);
				values.put(TestResultConstants.SSID, context.getCurrentWifi().getSSID());
				WLANPollManager.getWLANPollManager().updateTestResult(application.getApplicationContext(), 
						context.getCurrentWifi().getBSSID(), values);
				
				Toast.makeText(PollAutoTestActivity.this, "结果保存成功!", Toast.LENGTH_LONG).show();
			}
		});
	}

	private void updateButtonStatus() {
		if(currentStatus == EnumAutoTestStatus.STOPPED ||
				currentStatus == EnumAutoTestStatus.NOTSTART ||
				innerStatus == EnumAutoTestStatus.INNER_TEST_DHCP_STOPPED ||
				innerStatus == EnumAutoTestStatus.INNER_TEST_PING_STOPPED ||
				innerStatus == EnumAutoTestStatus.INNER_TEST_THROUGHTRATES_STOPPED) {
			
			btnReDhcpTest.setVisibility(View.VISIBLE);
			btnPingTest.setVisibility(View.VISIBLE);
			btnThroughtputRates.setVisibility(View.VISIBLE);
			
			return;
		}
		
		if(currentStatus == EnumAutoTestStatus.AUTO_TEST_DHCP ||
				currentStatus == EnumAutoTestStatus.AUTO_TEST_PING ||
				currentStatus == EnumAutoTestStatus.AUTO_TEST_THROUGHTRATES) {
			btnReDhcpTest.setVisibility(View.GONE);
			btnPingTest.setVisibility(View.GONE);
			btnThroughtputRates.setVisibility(View.GONE);			
			return;
		}
		
		if(currentStatus == EnumAutoTestStatus.RE_TEST_DHCP) {
			btnReDhcpTest.setVisibility(View.GONE);
			btnPingTest.setVisibility(View.GONE);
			btnThroughtputRates.setVisibility(View.GONE);
			return;
		} 
		
		if(currentStatus == EnumAutoTestStatus.RE_TEST_PING) {
			btnReDhcpTest.setVisibility(View.GONE);
			btnPingTest.setVisibility(View.GONE);
			btnThroughtputRates.setVisibility(View.GONE);
			return;
		}
		
		if(currentStatus == EnumAutoTestStatus.RE_TEST_THROUGHTRATES) {
			btnReDhcpTest.setVisibility(View.GONE);
			btnPingTest.setVisibility(View.GONE);
			btnThroughtputRates.setVisibility(View.GONE);	
			return;
		}
	}
	
	private void sendUpdateButtonStatus() {
		Message message = new Message();
		message.what = UPDATE_BUTTON_STATUS;
		updateUIHandler.sendMessage(message);
	}
	
	private void startAutoTest() {
		if (currentStatus == EnumAutoTestStatus.NOTSTART
				|| currentStatus == EnumAutoTestStatus.NOTSTART) {

			if (autoTestThread != null && autoTestThread.isAlive()) {
				autoTestThread.interrupt();
			}
			
			currentAutoTestStepIndex = 1;
			autoTestThread = new Thread(new AutoTestWorkerThread());
			autoTestThread.start();
			btnStartTest.setVisibility(View.GONE);
			txtHit.setVisibility(View.VISIBLE);
			txtHit.setText("开始自动测试");
			
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		sendUpdateButtonStatus();
	}

	/**
      * DHCP测试
      */
	private void startToTestDhcp() {
		// 使用线程先断开网络，然后重新获取IP地址
		innerStatus = EnumAutoTestStatus.INNER_TEST_DHCP_STARTED;

		TestSatus status = new TestSatus(currentStep, innerStatus);
		status.setObj(null);
		Message msg = new Message();
		msg.obj = status;
		msg.what = UPDATE_DHCP_INFO;
		updateUIHandler.sendMessage(msg);
		
		reDhcpTime = System.currentTimeMillis();
		wifiManager.reassociate();
	}
	
	/**
	 * Ping测试
	 */
	private void startToTestPing() {
		// ping网关和指定的地址，记录ping的结果
		innerStatus = EnumAutoTestStatus.INNER_TEST_PING_STARTED;
		WifiManager wifiManager = (WifiManager)getSystemService(WIFI_SERVICE);
		DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
		gatewayIp = NetworkUtils.intToIp(dhcpInfo.gateway);
		SystemSetting systemSetting = application.getContext().getSystemSetting();
		
		PingExecuteTask task = null;
		if(systemSetting.getPingParams() == null) {
			task = new PingExecuteTask(this, gatewayIp, 5,
				"gateway");
		} else {
			task = new PingExecuteTask(this, gatewayIp, systemSetting.getPingParams(), "gateway");
		}
		
		Thread thread = new Thread(task);
		thread.start();
		
		sendUpdateButtonStatus();
	}

	/**
	 * ThroughtOutRate测试
	 */
	private void startToTestThroughtOutRates() {
		// 执行一个HTTP请求,记录下载的平均时间
		innerStatus = EnumAutoTestStatus.INNER_TEST_THROUGHTRATES_STARTED;

		ThroughtOuputputRatesExceuteTask task = new ThroughtOuputputRatesExceuteTask(
				application.getContext().getSystemSetting().getThroughtoutputTestUrl(), this, "throught_test");
		Thread thread = new Thread(task);
		thread.start();
		
		sendUpdateButtonStatus();
	}

	private void setTestHit() {
		if (currentStatus != EnumAutoTestStatus.NOTSTART
				&& currentStatus != EnumAutoTestStatus.STOPPED) {
			if (txtHit.getVisibility() != View.VISIBLE) {
				txtHit.setVisibility(View.VISIBLE);
			}
		}

		if (currentStatus == EnumAutoTestStatus.AUTO_TEST_PING
				|| currentStatus == EnumAutoTestStatus.RE_TEST_PING) {
			txtHit.setText("正在执行Ping测试");
		} else if (currentStatus == EnumAutoTestStatus.AUTO_TEST_DHCP
				|| currentStatus == EnumAutoTestStatus.RE_TEST_DHCP) {
			txtHit.setText("正在执行DHCP测试");
		} else if (currentStatus == EnumAutoTestStatus.AUTO_TEST_THROUGHTRATES
				|| currentStatus == EnumAutoTestStatus.RE_TEST_THROUGHTRATES) {
			txtHit.setText("正在执行吞吐率测试");
		} else if (currentStatus == EnumAutoTestStatus.NOTSTART
				|| currentStatus == EnumAutoTestStatus.STOPPED) {
			txtHit.setVisibility(View.GONE);
		}
	}

	private void setDHCPInfo(Message message) {
		TestSatus status = (TestSatus) message.obj;
		DhcpInfo dhcpInfo = (DhcpInfo) status.getObj();

		if (status.getInnerStatus() == EnumAutoTestStatus.INNER_TEST_DHCP_STARTED) {
			txtIp.setText("正在获取IP地址...");
		} else if (status.getInnerStatus() == EnumAutoTestStatus.INNER_TEST_DHCP_STOPPED) {
			if (dhcpInfo != null) {
				txtIp.setText(NetworkUtils.intToIp(dhcpInfo.ipAddress));
			} else {
				txtIp.setText("未知IP");
			}
			//设置时长
			TextView dhcpTime = (TextView)findViewById(R.id.txtReDhcpTime);
			dhcpTime.setText("重新获取IP共耗时" + reDhcpTime/1000 + "秒");
		}
	}

	private void setPingGateWayInfo(Message message) {
		String line = (String) message.obj;
		TextView txtGatewayIp = (TextView)findViewById(R.id.txtGatewayIp);
		txtGatewayIp.setText("网关地址:" + gatewayIp);
		
		if(line != null) {
			txtPingCmd1.append(line + "\n");
		} else {
			if(gatewayPkgLost != null) {
				TextView textView = (TextView)findViewById(R.id.gatewayPkgLost);
				textView.setText(gatewayPkgLost);
			}
			
			if(gatewayLost != null) {
				TextView textView = (TextView)findViewById(R.id.gatewayLost);
				textView.setText(gatewayLost + "%");
			}
			
			if(gatewayDelay != null) {
				TextView textView = (TextView)findViewById(R.id.gatewayDelay);
				textView.setText(gatewayDelay + "ms");
			} 
			
			if(gatewayMaxDelay != null) {
				TextView textView = (TextView)findViewById(R.id.gatewayMaxDelay);
				textView.setText(gatewayMaxDelay + "ms");
			}

			if(gatewayMinDelay != null) {
				TextView textView = (TextView)findViewById(R.id.gatewayMinDelay);
				textView.setText(gatewayMinDelay + "ms");
			}
		}
	}

	private void setPingAdslInfo(Message message) {
		String line = (String) message.obj;
		TextView txtAdslIp = (TextView)findViewById(R.id.txtAdslIp);
		txtAdslIp.setText("宽带地址:" + adslIp);
		
		if(line != null) {
			txtPingCmd2.append(line + "\n");	
		} else {
			if(adslLost != null) {
				TextView textView = (TextView)findViewById(R.id.adslLost);
				textView.setText(adslLost + "%");
			}
			

			if(adslPkgLost != null) {
				TextView textView = (TextView)findViewById(R.id.adslPkgLost);
				textView.setText(adslPkgLost);
			}

			if(adslDelay != null) {
				TextView textView = (TextView)findViewById(R.id.adslDelay);
				textView.setText(adslDelay + "ms");
			} 

			
			if(adslMaxDelay != null) {
				TextView textView = (TextView)findViewById(R.id.adslMaxDelay);
				textView.setText(adslMaxDelay + "ms");
			}
			
			if(adslMinDelay != null) {
				TextView textView = (TextView)findViewById(R.id.adslMinDelay);
				textView.setText(adslMinDelay + "ms");
			}
		}
	}

	@Override
	public void onProgressUpdate(String tag, String line) {
		if ("gateway".equals(tag)) {
			// update ui.
			Message msg = new Message();
			msg.what = UPDATE_PING_GATEWAY;
			msg.obj = line;
			updateUIHandler.sendMessage(msg);
			String result[] = PingUtils.parsePingResultParse(line);
			if(result != null && result.length == 6) {
				if(result[1] != null) {
					//最小延迟
					gatewayMinDelay = result[1];
				} 
				if(result[4] != null) {
					//平均延迟
					gatewayDelay = result[4];
				} 
				if(result[5] != null) {
					//最大延迟
					gatewayMaxDelay = result[5];
				} 
				if(result[2] != null) {
					gatewayLost = result[2];
				} 
				if(result[3] != null) {
					gatewayPkgLost = result[3];
				}
			}
		} else if ("adsl".equals(tag)) {
			Message msg = new Message();
			msg.what = UPDATE_PING_ADSL;
			msg.obj = line;
			updateUIHandler.sendMessage(msg);
			String result[] = PingUtils.parsePingResultParse(line);
			if(result != null && result.length == 6) {
				if(result[1] != null) {
					//最小延迟
					adslMinDelay = result[1];
				} 
				if(result[4] != null) {
					//平均延迟
					adslDelay = result[4];
				} 
				if(result[5] != null) {
					//最大延迟
					adslMaxDelay = result[5];
				} 
				if(result[2] != null) {
					adslLost = result[2];
				} 
				if(result[3] != null) {
					adslPkgLost = result[3];
				}
			}
		}	
	}

	@Override
	public void onPingOver(String tag, String msg, Throwable exp) {
		if ("gateway".equals(tag)) {
			SystemSetting systemSetting = application.getContext().getSystemSetting();
			if(systemSetting.getAdslServerAdress() != null) {
				adslIp = systemSetting.getAdslServerAdress();
			} else {
				adslIp = WLanPollingUtils.DEBUG_IP;
			}
			
			Message message = new Message();
			message.what = UPDATE_PING_GATEWAY;
			message.obj = null;
			updateUIHandler.sendMessage(message);
			
			PingExecuteTask task = null;
			if(systemSetting.getPingParams() == null) {
				task = new PingExecuteTask(this, adslIp, 5,
					"adsl");
			} else {
				task = new PingExecuteTask(this, adslIp, systemSetting.getPingParams(), "adsl");
			}
			
			Thread thread = new Thread(task);
			thread.start();
			
		} else if ("adsl".equals(tag)) {
			Message message = new Message();
			message.what = UPDATE_PING_ADSL;
			message.obj = null;
			updateUIHandler.sendMessage(message);
			
			innerStatus = EnumAutoTestStatus.INNER_TEST_PING_STOPPED;
			currentAutoTestStepIndex++;
		}
		
		sendUpdateButtonStatus();
	}

	@Override
	public void onProgress(String tag, int downloadedSize, int time, int[] speeds) {
		Message msg = new Message();
		msg.what = UPDATE_THROUGHTOUT_CHART;
		msg.obj = new Object[]{time, speeds};
		
		throughtoutputRateAverageSpeed = speeds[1];
		throughtoutputRatePeakSpeed = speeds[2];
		
		updateUIHandler.sendMessage(msg);
	}

	@Override
	public void onExecuteOver(String tag, int downloadedSize, int totalTime,
			int averageSpeed, Throwable exp) {
		Log.d(PollAutoTestActivity.class.getName(), "onExecuteOver" + tag + " "
				+ downloadedSize + " " + totalTime + " " + averageSpeed);
		currentAutoTestStepIndex++;
		innerStatus = EnumAutoTestStatus.INNER_TEST_THROUGHTRATES_STOPPED;
		sendUpdateButtonStatus();
	}

	private void updateHit() {
		Message message = new Message();
		message.what = UPDATE_HIT;
		updateUIHandler.sendMessage(message);
	}

	class AutoTestWorkerThread implements Runnable {

		@Override
		public void run() {
			while (true) {
				if (currentAutoTestStepIndex >= autoTestSteps.length) {
					Log.d(PollAutoTestActivity.class.getName(),
							"AutoTestWorkerThread is stopped");
					resetStatus();
					updateHit();
					break;
				}

				if (autoTestSteps[currentAutoTestStepIndex] == EnumAutoTestStatus.AUTO_TEST_DHCP
						&& innerStatus != EnumAutoTestStatus.INNER_TEST_DHCP_STARTED) {
					currentStatus = EnumAutoTestStatus.AUTO_TEST_DHCP;
					sendUpdateButtonStatus();
					currentStep = currentStatus;
					innerStatus = currentStep;
					updateHit();
					startToTestDhcp();
				} else if (autoTestSteps[currentAutoTestStepIndex] == EnumAutoTestStatus.AUTO_TEST_PING
						&& innerStatus != EnumAutoTestStatus.INNER_TEST_PING_STARTED) {
					currentStatus = EnumAutoTestStatus.AUTO_TEST_PING;
					currentStep = currentStatus;
					innerStatus = currentStep;
					updateHit();
					startToTestPing();
				} else if (autoTestSteps[currentAutoTestStepIndex] == EnumAutoTestStatus.AUTO_TEST_THROUGHTRATES
						&& innerStatus != EnumAutoTestStatus.INNER_TEST_THROUGHTRATES_STARTED) {
					currentStatus = EnumAutoTestStatus.AUTO_TEST_THROUGHTRATES;
					currentStep = currentStatus;
					innerStatus = currentStep;
					updateHit();
					startToTestThroughtOutRates();
				}
				sendUpdateButtonStatus();
				if (autoTestSteps[currentAutoTestStepIndex] == currentStep) {
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						resetStatus();
						break;
					}
				}
			}
		}

		private void resetStatus() {
			// TODO
			currentAutoTestStepIndex = 0;
			currentStatus = EnumAutoTestStatus.NOTSTART;
			currentStep = EnumAutoTestStatus.NOTSTART;
			
			sendUpdateButtonStatus();
		}
	}

	class WifiBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			NetworkInfo networkInfo = (NetworkInfo) intent
					.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
			if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				State state = networkInfo.getState();
				if (state == State.CONNECTED) {
					// 设置
					DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();

					if (innerStatus == EnumAutoTestStatus.INNER_TEST_PING_STARTED)
						innerStatus = EnumAutoTestStatus.INNER_TEST_DHCP_STOPPED;

					if (currentStatus == EnumAutoTestStatus.RE_TEST_DHCP) {
						currentStatus = EnumAutoTestStatus.STOPPED;
						TestSatus status = new TestSatus(
								EnumAutoTestStatus.RE_TEST_DHCP,
								EnumAutoTestStatus.INNER_TEST_DHCP_STOPPED);
						status.setObj(dhcpInfo);
						Message msg = new Message();
						msg.obj = status;
						msg.what = UPDATE_DHCP_INFO;
						reDhcpTime = System.currentTimeMillis() - reDhcpTime;
						updateUIHandler.sendMessage(msg);
					} else if (currentStatus == EnumAutoTestStatus.AUTO_TEST_DHCP) {
						// 更新UI
						TestSatus status = new TestSatus(
								EnumAutoTestStatus.AUTO_TEST_DHCP,
								EnumAutoTestStatus.INNER_TEST_DHCP_STOPPED);
						status.setObj(dhcpInfo);
						Message msg = new Message();
						msg.obj = status;
						msg.what = UPDATE_DHCP_INFO;
						reDhcpTime = System.currentTimeMillis() - reDhcpTime;
						updateUIHandler.sendMessage(msg);
						// 自动测试下一项
						currentAutoTestStepIndex++;
					}
				} else if (state == State.DISCONNECTED) {

				}
				sendUpdateButtonStatus();
				Log.d(WifiBroadcastReceiver.class.getName(), "wifi's state = "
						+ state);
			}
		}

	}

	class UpdateUIHandler extends Handler {

		public UpdateUIHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == UPDATE_HIT) {
				setTestHit();
				return;
			}

			if (msg.what == UPDATE_DHCP_INFO) {
				setDHCPInfo(msg);
				return;
			}

			if (msg.what == UPDATE_PING_GATEWAY) {
				setPingGateWayInfo(msg);
			}

			if (msg.what == UPDATE_PING_ADSL) {
				setPingAdslInfo(msg);
			}

			if (msg.what == UPDATE_THROUGHTOUT_CHART) {
				if (chartView != null) {
					Object[] obj = (Object[])msg.obj;
					int[] speeds = (int[])obj[1];
					dataset.getSeriesAt(0).add((Integer)obj[0], speeds[1]);

					if(rendererMaxY < speeds[1]) {
						rendererMaxY = speeds[1] + 10;
						renderer.setYAxisMax(rendererMaxY);
					}
					
					int currentTime = (Integer)obj[0];
					
					if(currentTime > rendererMaxX) {
						rendererMaxX = currentTime + 10;
						renderer.setXAxisMax(rendererMaxX);
					}
					
					if(currentTime % 5 == 0) {
						renderer.addXTextLabel(currentTime, currentTime + "");
					}
					
					chartView.invalidate();
				}

				//平均速度
				txtWebAverageSpeed = (TextView)findViewById(R.id.txtWebAverageSpeed);
				txtWebAverageSpeed.setText(throughtoutputRateAverageSpeed/1024 + "KB/s");
				
				txtWebPeekSpeed = (TextView)findViewById(R.id.txtWebPeekSpeed);
				txtWebPeekSpeed.setText(throughtoutputRatePeakSpeed/1024 + "KB/s");
			}
			
			if(msg.what == UPDATE_BUTTON_STATUS) {
				updateButtonStatus();
			}
		}
	}
}

class TestSatus {
	private EnumAutoTestStatus step;
	private EnumAutoTestStatus innerStatus;
	private Object obj;

	public TestSatus(EnumAutoTestStatus step, EnumAutoTestStatus innerStatus) {
		this.step = step;
		this.innerStatus = innerStatus;
	}

	public EnumAutoTestStatus getStep() {
		return step;
	}

	public EnumAutoTestStatus getInnerStatus() {
		return innerStatus;
	}

	public Object getObj() {
		return obj;
	}

	public void setObj(Object obj) {
		this.obj = obj;
	}
}

/**
 * 测试状态
 * 
 * @author Bean
 * 
 */
enum EnumAutoTestStatus {
	NOTSTART, STOPPED,

	AUTO_TEST_DHCP, 
	AUTO_TEST_PING, 
	AUTO_TEST_THROUGHTRATES,

	RE_TEST_DHCP, 
	RE_TEST_PING, 
	RE_TEST_THROUGHTRATES,

	INNER_TEST_DHCP_STARTED, 
	INNER_TEST_DHCP_STOPPED, 
	INNER_TEST_PING_STARTED, 
	INNER_TEST_PING_STOPPED, 
	INNER_TEST_THROUGHTRATES_STARTED, 
	INNER_TEST_THROUGHTRATES_STOPPED;
}
